#include "mongoc_const.h"
#include "mongoc_data.h"
#include <stdio.h>

int amdar_mongoc_insert_platform(int *cid, const char *name) {
  if (*cid >= nbundle) {
    return FORTRAN_MONGO_MEMORY_ERROR;
  }
  struct MongoObjectBundle *bundle = &bundles[*cid];

  bson_t *doc;
  bson_error_t error;

  doc = BCON_NEW(
    "sid", BCON_UTF8(name)
  );

  if (!mongoc_collection_insert_one(bundle->col, doc, NULL, NULL, &error)) {
    bson_destroy(doc);
    if (error.code == MONGOC_ERROR_DUPLICATE_KEY) {
      return FORTRAN_MONGO_INSERT_DUP_WARN;
    } else {
      printf("%s\n", name);
      printf("[Error]: amdar_mongoc_insert_platform: %s\n", error.message);
      return FORTRAN_MONGO_INSERT_ERROR;
    }
  }

  bson_destroy(doc);

  return FORTRAN_MONGO_NO_ERROR;
}

int amdar_mongoc_insert_record(int *cid, const char *name, double *timestamp,
                               float *lon, float *lat, float *z, float *ta,
                               float *ps, float *sh, float *ua, float *va) {
  if (*cid >= nbundle) {
    return FORTRAN_MONGO_MEMORY_ERROR;
  }
  struct MongoObjectBundle *bundle = &bundles[*cid];

  bson_t *doc;
  bson_error_t error;
 
  doc = BCON_NEW(
    "sid" , BCON_UTF8(name),
    "time", BCON_DATE_TIME(*timestamp * 1000), // UTC time
    "location", "{",
      "type", "Point",
      "coordinates", "[", BCON_DOUBLE(*lon), BCON_DOUBLE(*lat), "]",
    "}",
    "z", BCON_DOUBLE(*z),
    "ta"  , BCON_DOUBLE(*ta),
    "p"   , BCON_DOUBLE(*ps),
    "sh"  , BCON_DOUBLE(*sh),
    "ua"  , BCON_DOUBLE(*ua),
    "va"  , BCON_DOUBLE(*va)
  );

  if (!mongoc_collection_insert_one(bundle->col, doc, NULL, NULL, &error)) {
    bson_destroy(doc);
    if (error.code == MONGOC_ERROR_DUPLICATE_KEY) {
      return FORTRAN_MONGO_INSERT_DUP_WARN;
    } else {
      printf("%s\n", name);
      printf("[Error]: amdar_mongoc_insert_record: %s\n", error.message);
      return FORTRAN_MONGO_INSERT_ERROR;
    }
  }

  bson_destroy(doc);

  return FORTRAN_MONGO_NO_ERROR;

}
